﻿CREATE FUNCTION QIC.KeyResolve_DEFAULT (@Token QIC.TokenTable READONLY, @CallerId INT, @CalleeId INT, @TokenMap VARCHAR(50))
RETURNS @Keys TABLE (CallerPropertyName VARCHAR(50), CalleePropertyName VARCHAR(50))
AS
BEGIN

	DECLARE @KeyName VARCHAR(100)
	DECLARE @CallerName VARCHAR(100)

	SELECT @CallerName = OBJECT_NAME(@CallerId)

	DECLARE @MatchKeys TABLE (Id tinyint IDENTITY(1,1), CallerPropertyName VARCHAR(50), CalleePropertyName VARCHAR(50))

	INSERT INTO @MatchKeys (CallerPropertyName, CalleePropertyName) VALUES
	(@CallerName + 'ID', @CallerName + 'ID'),
	(REPLACE(@CallerName,'_','') + 'ID',REPLACE(@CallerName,'_','') + 'ID'),
	('ID','ID'),
	('ID', @CallerName + 'ID'),
	('ID',REPLACE(@CallerName,'_','') + 'ID')

	INSERT INTO @Keys (CallerPropertyName,CalleePropertyName)
	SELECT TOP 1 callerToken.PropertyName, calleeToken.PropertyName FROM @MatchKeys matchkeys
	inner join @Token callerToken
		on callerToken.ObjectId = @CallerId
		and callerToken.PropertyName = matchkeys.CallerPropertyName
	inner join @Token calleeToken
		on calleeToken.ObjectId = @CalleeId
		and calleeToken.PropertyName = matchkeys.CalleePropertyName
	order by matchkeys.Id

	RETURN

END
